<!--
 * @Author: 睡衣船长 121771372@qq.com
 * @Date: 2023-10-25 21:42:34
 * @LastEditors: Mr.wangxf 2712638312@qq.com
 * @LastEditTime: 2023-11-15 18:38:29
 * @Description: 更新任务部门、执行人、时间等浮窗
-->
<template>
  <xr-dialog-float
    v-bind="updateTaskParams"
    v-model="updateTaskVisible"
  >
    <template v-if="updateType == 'department'">
      <div class="department scrollClass">
        <el-cascader
          v-model="chooseDepartment"
          ref="departmentListRef"
          popper-class="depPopper"
          :options="departmentList"
          :props="{ children: 'subOrgList', value: 'id', label: 'orgName', checkStrictly: true }"
          @change="updateChooseDepartment"
          @visible-change="(value) => { console.log('visibleChange', value) }"
        />
      </div>
    </template>
    <template v-else-if="updateType == 'executor'">
      <div class="executor scrollClass">
        <div
          class="item flex-left-center"
          v-for="item, i in executorList"
          :class="chooseExecutor == item.userId ? 'active' : ''"
          :key="i"
          @click="updateChooseExecutor(Number(item.userId) || 0)"
        >
          <div class="name text-ellipsis-line-clamp-two">{{ item.user.nickName }}</div>
        </div>
        <div
          class="empty flex flex-column"
          v-if="executorList.length == 0"
        >
          <img :src="_getImg('gap-task-executor-empty.png')">
          <span>暂无数据</span>
        </div>
      </div>
    </template>
    <template v-else-if="updateType == 'time'">
      <div class="time">
        <div class="title">持续时长（天）</div>
        <el-input-number
          class="timeInput"
          v-model="chooseTaskDay"
          :min="0"
          :max="999"
          controls-position="right"
          size="large"
        />
        <div
          class="sure"
          @click="updateChooseTaskDay"
        >确定</div>
      </div>
    </template>
    <template v-else-if="updateType == 'startTime'">
      <div class="startTime">
        <xr-date
          v-model="chooseStartTime"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          @change="updateChooseStartTime"
        ></xr-date>
        <!-- <gap-date-picker
          class="date-picker"
          v-model="chooseStartTime"
          type="datetime"
          format="YYYY-MM-DD HH:mm"
          valueFormat="YYYY-MM-DD HH:mm:ss"
          @update:model-value="updateChooseStartTime"
        ></gap-date-picker> -->
      </div>
    </template>
  </xr-dialog-float>
</template>
<script lang="ts" setup>
import { reactive, Ref, ref, computed, watch, nextTick } from 'vue'
import { _getImg, _canObject } from '@/utils'
import type { ElCascader } from 'element-plus'
import { fetchOrgUserList } from '@/api/departmentManage/orgUser'
import { useOrgStore } from '@/pinia/org'
import { apiUpdateTask, apiUpdateTemplateTask } from '@/api/raiseShop/task'

const props = defineProps({
  taskDetail: {
    type: Object,
    default: () => { }
  },
  isTemplate: {
    type: Boolean,
    default: false
  }
})

const updateTaskParams = reactive({
  hasHeader: false,
  left: '0px',
  top: '0px'
})
const updateTaskVisible: Ref<boolean> = ref(false)
const updateType: Ref<string> = ref('')
const departmentListRef = ref()
// 组件方法
const showDialog = async (type: string, left: string, top: string) => {
  updateTaskVisible.value = true
  updateType.value = type
  updateTaskParams.left = left
  updateTaskParams.top = top
  console.log(type, 'showDialog', left, top)
  if (type == 'executor') {
    if (chooseDepartment.value[0] == '0') {
      // 选择门店
      // const res = await gapFlowTableUserApi._api.listOfNoRepeatMember(params)
      // res.forEach(item => {
      //   item.id = item.memberId + ''
      //   item.opName = item.memberName
      // })
      // executorList.value = res
    } else {
      const orgId = props.taskDetail.organizationId
      executorList.value = await getUserList(orgId)
    }
  }
  if (type == 'department') {
    useOrgStore().getOrgList().then((res: any) => {
      departmentList.value = res
    })
    setTimeout(() => {
      departmentListRef.value.togglePopperVisible(true)
    }, 50);
  }
}

const getUserList = async (orgId: Bus_StringNo) => {
  if (!orgId) return []
  const res: any = await fetchOrgUserList({ orgId })
  console.log(res, 'getUserList')
  if (!_canObject(res) && !res?.length) return []
  return Promise.resolve(res)
}

const departmentList = ref([])


const hideDialog = () => {
  updateTaskVisible.value = false
}
const getPosition = () => {
  return {
    left: updateTaskParams.left?.replace('px', ''),
    top: updateTaskParams.top?.replace('px', '')
  }
}
const setPosition = (left: string, top: string) => {
  updateTaskParams.left = left
  updateTaskParams.top = top
}

const chooseDepartment: Ref<Array<Bus_StringNo>> = ref([])
// 编辑时设置初始值
// const setChooseDepartment = (val: number) => {
//   chooseDepartment.value = val.toString()
// }
// 修改门店
const updateChooseDepartment = async () => {
  const organizationId = chooseDepartment.value[chooseDepartment.value.length - 1] || ''
  await updateTaskDetail({
    organizationId,
    executorId: ''
  })
  hideDialog()
  emit('onUpdate')
}
// 设置执行人
const executorList = ref<any>([])
const chooseExecutor: Ref<Bus_StringNo> = ref('')

// 修改执行人
const updateChooseExecutor = async (val: number) => {
  await updateTaskDetail({
    executorId: val
  })
  hideDialog()
  emit('onUpdate')
}
// 设置持续时长
const chooseTaskDay: Ref<number> = ref(0)

// 修改持续时长
const updateChooseTaskDay = async () => {
  await updateTaskDetail({
    taskDay: chooseTaskDay.value
  })
  hideDialog()
  emit('onUpdate')
}
// 设置开始时间
const chooseStartTime = ref('')

// 修改开始时间
const updateChooseStartTime = async () => {
  await updateTaskDetail({
    startTime: chooseStartTime.value
  })
  hideDialog()
  emit('onUpdate')
}

const emit = defineEmits<{
  (e: 'onUpdate'): void,
}>()

const departmentListRefVisible = computed(() => {
  if (updateTaskVisible.value && updateType.value == 'department') {
    return true
  } else {
    return false
  }
})

const updateTaskDetail = async (newParams: any) => {
  if (!props.taskDetail.id) return
  const params: any = {
    id: props.taskDetail.id,
    organizationId: props.taskDetail.organizationId,
    organizationType: props.taskDetail.organizationType || 2,
    startTime: props.taskDetail.startTime,
    taskName: props.taskDetail.taskName,
    executorId: props.taskDetail.executorId,
    endTime: props.taskDetail.endTime,
    completeTime: props.taskDetail.completeTime,
    taskDescription: props.taskDetail.taskDescription,
    repeatType: props.taskDetail.repeatType,
    taskDay: props.taskDetail.taskDay,
    actualStartTime: props.taskDetail.actualStartTime,
    isNeedAcceptance: props.taskDetail.isNeedAcceptance,
    intervalTime: props.taskDetail.intervalTime,
    ...newParams
  }
  if (props.isTemplate) {
    params.taskSource = props.taskDetail.taskSource
  }
  const res = props.isTemplate ? await apiUpdateTemplateTask(params) : await apiUpdateTask(params)
  console.log(res, 'updateTaskDetail')
  // await refreshTaskDetail()
}

defineExpose({
  showDialog,
  hideDialog,
  getPosition,
  setPosition
})
</script>
<style lang="scss">
.depPopper {
  border-radius: 12px !important;
  box-shadow: 0px 0px 50px 0px rgb(82 63 105 / 15%) !important;
  border: 1px solid transparent !important;

  .el-popper__arrow {
    display: none;
  }

  .el-radio__inner:hover {
    border-color: #04C8C8;
  }

  .el-radio__input.is-checked .el-radio__inner {
    border-color: #04C8C8;
    background-color: #04C8C8;
  }

  .el-cascader-node {
    color: #5E6278;
  }

  .el-cascader-node.in-active-path,
  .el-cascader-node.is-active,
  .el-cascader-node.is-selectable.in-checked-path {
    color: #04C8C8;
  }

  .el-cascader-node {
    padding: 0 16px;
    padding-right: 16px !important;
  }
}
</style>
<style lang="scss" scoped>
.department {
  width: 0px;
  position: relative;
  top: -44px;
  opacity: 0;
}

.executor {
  width: 200px;
  height: 204px;
  padding: 12px 0;
  overflow: auto;
  color: #5e6278;

  .item {
    width: 100%;
    height: 36px;
    padding: 0 16px;

    .name {
      font-size: 14px;
    }
  }

  .item:hover,
  .item.active {
    background-color: #f5f8fa;

    .name {
      color: #04c8c8;
    }
  }

  .empty {
    height: 100%;

    img {
      width: 160px;
      height: 98px;
    }

    span {
      margin-top: 8px;
      color: #7e8299;
      font-size: 13px;
    }
  }
}

.time {
  width: 280px;
  height: 150px;
  border-radius: 16px;
  padding: 16px;

  .title {
    height: 22px;
    line-height: 22px;
    font-size: 14px;
    color: #3f4254;
  }

  .timeInput {
    width: 100%;
    margin-top: 8px;

    :deep(.el-input__wrapper) {
      background-color: #f5f8fa;
    }
  }

  .sure {
    margin-top: 16px;
    text-align: center;
    height: 36px;
    line-height: 36px;
    background-color: #04c8c8;
    color: white;
    border-radius: 8px;
    font-size: 14px;
  }
}
</style>